package net.eldeen.stockhack.service;

import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import net.eldeen.stockhack.model.Stock;

import org.apache.commons.digester.Digester;
import org.apache.commons.digester.xmlrules.DigesterLoader;
import org.apache.log4j.Logger;
import org.xml.sax.SAXException;


public class StockDigester {
	
	private static final Logger LOGGER = Logger.getLogger(StockDigester.class);
	
	private Digester digester;

	public void init() {
		URL rules = getClass().getResource("./stock-rules.xml");
		digester = DigesterLoader.createDigester(rules);
	}

	public List<Stock> digest(String input) throws IOException, SAXException {
		// Push empty List onto Digester's Stack
		List<Stock> stocks = new ArrayList<Stock>();
		digester.push( stocks );
		
		// Parse the XML document
		digester.parse(new StringReader(input));
		LOGGER.debug("got stocks: " + stocks.size());
		
		return stocks;
	}
}
